<?php
	/**
	* 发送短信 生成短信日志	2017-12-14
	* @param $mobilephone 手机号  $RandParam 短信内容
	*/
	function messagelog($mobilephone,$RandParam,$uid=0){
		$Message = vendor('ZZYMessage.Message');
		$Message = new \Message(['accountsid'=>C('USID'),'token'=>C('UTOKEN')]);
		$result = $Message -> SendSms(C('APPID'),C('EXAMPLEID'),$RandParam,$mobilephone,$uid);
		return $result;
	}

	/**
	* 生成验证码	2017-12-14
	*/
	function createverifycode($length = 4){
		$number = "";
		for ($i = 0;$i < $length;$i++){
			$number .= rand(0,9);
		}
		return $number;
	}
	
	function serializeMysql($info,$type = 0){
	    if($type == 0){
	        return addslashes(serialize($info));
	    }else {
	        return unserialize(stripslashes($info));
	    }
	}

	/**
	 * 手机号验证 2017-12-14
	 */
	function check_mobilephone($mobilehone = ''){
		if(preg_match("/1[34578]{1}\d{9}$/",$mobilehone)){
			return true;
		}else{
			return false;
		}
	}
	function createObjectDir($dir_name) {
		Vendor('OSS.autoload');//引入文件
		$accessKeyId = C('ACCESSKEYID'); 
		$accessKeySecret = C('ACCESSKEYSECRET');
		$endpoint = C('ENDPOINT');
		$bucket=C('BUCKET');
		try{
			$ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$ossClient->createObjectDir($bucket, $dir_name);
		} catch(OssException $e) {
			return false;
		}
	}
	function ossPutObject($file_name,$content){
		Vendor('OSS.autoload');//引入文件
		$accessKeyId = C('ACCESSKEYID'); 
		$accessKeySecret = C('ACCESSKEYSECRET');
		$endpoint = C('ENDPOINT');
		$bucket=C('BUCKET');
		try {
			$ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$result = $ossClient->putObject($bucket, $file_name, $content);
			return $result;
		} catch (OssException $e) {
			return false;
		}
	}

	function ossAppendObject($file_name, $content) {
        Vendor('OSS.autoload');//引入文件
        $accessKeyId = C('ACCESSKEYID');
        $accessKeySecret = C('ACCESSKEYSECRET');
        $endpoint = C('ENDPOINT');
        $bucket=C('BUCKET');

        try {
            $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $result = $ossClient -> appendObject($bucket, $file_name, $content,1);
            return $result;
        } catch (OssException $e) {
            return false;
        }
    }
	function deleteObject($file_name)
	{
		Vendor('OSS.autoload');//引入文件
        $accessKeyId = C('ACCESSKEYID');
        $accessKeySecret = C('ACCESSKEYSECRET');
        $endpoint = C('ENDPOINT');
        $bucket=C('BUCKET');
		try{
			$ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$ossClient->deleteObject($bucket, $file_name);
		} catch(OssException $e) {
			return;
		}
	}
    function doesObjectExist($file_name)
    {
        Vendor('OSS.autoload');//引入文件
        $accessKeyId = C('ACCESSKEYID');
        $accessKeySecret = C('ACCESSKEYSECRET');
        $endpoint = C('ENDPOINT');
        $bucket=C('BUCKET');
        try{
            $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $exist = $ossClient->doesObjectExist($bucket, $file_name);
            return $exist;
        } catch(OssException $e) {
            return false;
        }
    }
	/**
	 * 
	 */
	function ossGetObject($file_name){
		Vendor('OSS.autoload');// 引入文件
		$accessKeyId = C('ACCESSKEYID');
		$accessKeySecret = C('ACCESSKEYSECRET');
		$endpoint = C('ENDPOINT');
		$bucket=C('BUCKET');
		try {
			$ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$doesExist = $ossClient->doesObjectExist($bucket, $file_name);
			if($doesExist){
				$result = $ossClient->getObject($bucket, $file_name);
				return $result;
			}else{
				return false;
			}
		} catch (OssException $e) {
			return false;
		}
	}

	/**
	 * 生成原始的二维码(生成图片文件)  
	 */
	function scerweima($url='',$path=false,$name=""){
		// 二维码内容
	    $value = $url;
	    // 容错级别
	    $errorCorrectionLevel = 'L';
	    // 生成图片大小
	    $matrixPointSize = 12; 
	    if($path){
	    	$filename = $path;
	    }else{
	    	$filename = false;
	    }
	    try{
	    	// 生成二维码图片
	    	\Org\Util\QRcode::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, 1);
	    	// 准备好的logo图片
	    	$logo = C('PUBLIC_ROUTE').'/Public/mui/images/logo.png';
	    	// 准备好的背景图片
	    	// $back = C('PUBLIC_ROUTE').'/Public/mui/images/back.jpg';
	    	if ($logo !== FALSE) {
	    	  $back_res = imagecreatefromjpeg($back);
			  $QR = imagecreatefrompng($filename);
			  $logo = imagecreatefrompng($logo);
			  // 背景图片宽度
			  $back_width = imagesx($back_res);
			  // 背景图片宽度
			  $back_height = imagesy($back_res);
			  // 二维码图片宽度
			  $QR_width = imagesx($QR);
			  // 二维码图片高度
			  $QR_height = imagesy($QR);
			  // logo图片宽度
			  $logo_width = imagesx($logo);
			  // logo图片高度
			  $logo_height = imagesy($logo);
			  // logo
			  $logo_qr_width = $QR_width / 5;
			  $scale = $logo_width/$logo_qr_width;
			  $logo_qr_height = $logo_height/$scale;
			  $from_width = ($QR_width - $logo_qr_width) / 2;
			  // 背景图
			  $qr_back_width = $back_width / 3;
			  $scale_back = $QR_width/$qr_back_width;
			  $qr_back_height = $QR_height/$scale_back;
			  $from_back_width = ($back_width - $qr_back_width) / 2;
			  // 重新组合图片并调整大小 
			  imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
			}
			// 保存二维码图片
			imagejpeg($QR,$filename,100);
			
			// 重新组合图片并调整大小
			// imagecopyresampled($back_res, $QR, $from_back_width, $from_back_width+380, 0, 0, $qr_back_width, $qr_back_height, $QR_width, $QR_height);
			// // 保存图片
			// imagejpeg($back_res,$filename,100);
			if(file_exists($filename)){
		    	chmod($filename, 0777);
		    	$resimg = makeImg($filename,$name);
		    	return $filename;
		    }else{
		    	return false;
		    }
	    } catch(\Think\Exception $e){
	    	return false;
	    }
	    return true;
	}

	function makeImg($filename,$name)
    {
        // header("Content-Type:text/html; charset=utf-8");
        // header('Content-type: image/png');// 告诉浏览器，这个文件，是一个png图片
        //字体大小
        $size = 13;
        //字体类型，本例为黑体
        $font = "./Public/Home/fonts/songti.ttf";
        //显示的文字
        $waterImageUrl = 12345678;
        //1、创建画布
        $img = imagecreatefromjpeg($filename);// 加载已有图像
        // 二维码图片宽度
        $QR_width = imagesx($img);
        // var_dump($QR_width);die;
        $textcolor=imagecolorallocate($img,92,18,7);
        $daax = $name;
        //2、写字
        // $str = iconv("UTF-8","GBK",$daax);
        // imagettftext($img,$size,0,$QR_width/3.5,1120,$textcolor,$font,$daax);
        imagettftext($img,$size,0,$QR_width/2.32,266,$textcolor,$font,$daax);
        //保存图片至指定路径
        ImagePNG($img, $filename);
        imagedestroy($img);
        return true;
    }
	/**
	 * http状态码
	 */
	function HttpStatus($num,$print_i=false) {
		switch ($num) {
			case '404':
				header('HTTP/1.1 404 Not Found');
				$html = '<h1 style="position:absolute;top:50%;left:50%;">404 Not Found<h1>';
				break;
			case '403':
				header('HTTP/1.1 403 Forbidden');
				$html = '<h1 style="position:absolute;top:50%;left:50%;">403 Forbidden<h1>';
			    break;
			default:
				return true;
				break;
		}
		if(!$print_i){
			echo $html;
		}
		die;
	}

	/**
	 * 生成随机字符串
	 */
	function randomkeys($length,$type=false) {
	    $returnStr='';
	    switch ($type) {
	    	case '1':
	    		$pattern = '1234567890';
	    		break;
	    	case '2':
	    		$pattern = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
	    		break;
	    	case '3':
	    		$pattern = 'abcdefghijklmnopqrstuvwxyz';
	    		break;
	    	default:
	    		$pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
	    		break;
	    }
	    for($i = 0; $i < $length; $i ++) {
	        $returnStr .= $pattern {mt_rand ( 0, strlen($pattern)-2 )}; // 生成php随机数
	    }
	    return $returnStr;
	}

	/**
	 * curl post 模拟请求
	 */
	function HttpPost($url,$post_data) {
	    $curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);

		// 5秒超时
		curl_setopt($curl, CURLOPT_TIMEOUT, 5);

		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_HEADER, 0);

		$res = curl_exec($curl);
		if (curl_errno($curl)) {
			$res = curl_error($curl);
		}
		curl_close($curl);
		return $res;
	}

	/**
	 * base64 图片上传
	 * @param base64 存储的base64的string
	 * @param path 图片存储路径
	 * @param randstr 文件名随机字符串
	 */
	function Base64DecodeImage($base64,$path,$randstr='') {
		$base64_image = str_replace(' ', '+', $base64);
		if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)){
			if(!is_dir($path)){
				mkdir($path,0777,true);
			}
			//匹配成功
	        $image_name = uniqid().$randstr.'.'.$result[2];
	        $image_file = rtrim($path,'/').'/'.$image_name;
	        //服务器文件存储路径
	        if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))){
	            return $image_name;
	        }else{
	            return false;
	        }
		}else{
			return false;
		}
	}

	/**
	 * 测试输出
	 * @params  要输出的变量
	 */
	function dd() {
		$fields = func_get_args();
		echo '<pre>';
		$c = count($fields);
		if($c>1000){ var_dump(false,'dd方法不支持输出这么多数据哦！');die;}
		for ($i=0; $i < $c; $i++) { 
			var_dump($fields[$i]);
		}
     	echo '</pre>';
     	exit();
	}



	/**
	 * 单位转换
	 */
	function FormatMoney($money){
	    if($money >= 10000){
	     return sprintf("%.2f", $money/10000).'万';
	    }else{
	     return $money.'元';
	    }
	 }
	 /**
	  * 去除小数点
	  * @param  [type] $data [description]
	  * @return [type]       [description]
	  */
	function getPublicdian($data){
	    $arr = Array();
	    foreach ($data as $key => $value) {
	      $res = substr($value,1);
	      array_push($arr,$res);
	    }
	    return $arr;
	  }

	/**
	 * 带消息跳转页面
	 * @url string 要跳转的页面
	 * [@massage] arr 带的参数 
	 */
	function redirect_msg($url,$message=false)
	{
	  if($url==false) return false;
	  $url = ltrim($url,'/');
	  if($message){
	    foreach ($message as $key => $value) {
	      if(is_array($value)){
	        $_SESSION['RedirectMessage'][$key] = implode(',', urlencode($value));
	      }else{
	        $_SESSION['RedirectMessage'][$key] = urlencode($value);
	      }
	    }
	  }
	  exit('<script language="javascript">top.location.href="'.C('WEBURL').$url.'"</script>');
	}

	/**
	 * 获取session数据
	 */
	function getMassage($key1)
	{
	  $data = explode(',',$_SESSION['RedirectMessage'][$key1]);
	  $_SESSION['RedirectMessage'] = null;
	  if(empty($data)){
	    return false;
	  }
	  foreach ($data as $key => $value) {
	    $data[$key] = urldecode($value);
	  }
	  if(count($data)==1){
	    return $data[0];
	  }else{
	    return $data;
	  }
	}

	/**
	 * 图片旋转
	 * @param  [type] $filename [description]
	 * @param  [type] $degrees  "旋转角度"
	 * @return [type]           [description]
	 */
	function rotate($filename,$degres){
		$degrees = $degres % 4;
		switch ($degrees)
		{
		case 1:
		  $degrees = 270;
		  break;  
		case 2:
		  $degrees = 180;
		  break;
		case 3:
		  $degrees = 90;
		  break;
		case 4:
		  $degrees = 0;
		  break;
		default:
		  $degrees = 0;
		  break;
		}
		$ext = pathinfo($filename)['extension'];
        switch ($ext) {
            case 'jpg':
            case 'jpeg':
                $img = imagecreatefromjpeg($filename);
                $rotate = imagerotate($img, $degrees, 0);
        		@imagejpeg($rotate,$filename);
                break;
            case 'png':
                $img = imagecreatefrompng($filename);
                $rotate = imagerotate($img, $degrees, 0);
        		@imagepng($rotate,$filename);
                break;
            default:
                die('图片格式错误!');
                break;
        }
  //       //创建图像资源，以jpeg格式为例
  //       // var_dump($ext,'22222');die;
  //       //使用imagerotate()函数按指定的角度旋转
  //       $rotate = imagerotate($img, $degrees, 0);
  //       // header('content-type:image/jpeg');
  //       // header('Content-type: image/*');
  //       //旋转后的图片保存
  //       // imagejpeg($rotate);
  //       @imagejpeg($rotate,$filename);
		// // rotate($path.$identity_A_file,$identity_info['identity_Anum1']);
    }

    /**
     * 获取http头信息
     */
    function gethttpheader() {
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }


    /**
     * 数组转Excel文件
     * @param array $title 标题头
     * @param array $data 导出数据
     * @param max $sheetarray sheet名称
     * @param String $fileName 文件名称
     * @param String $savePath 文件存储路径
     * @param bool #isDown 是否下载
     * @return 文件路径
     */
    function ExportExcelTable($title=array(), $data=array(), $sheetarray='sheet', $fileName='', $savePath='./', $isDown=false) 
    {   
    	$new_file = "./Public/Uploads/ChannelCount/";
	    if(!file_exists($new_file)){
	        $res=mkdir($new_file, 0777,true);
	    }
        import("Org.Util.PHPExcel");
        $obj = new \PHPExcel();
        if(is_array($sheetarray)){
        	for ($i=0; $i < count($sheetarray); $i++) {
		    	ExportExcelSheet($obj,$title[$i],$data[$i],$sheetarray[$i],$i);
		    }
        }else{
        	ExportExcelSheet($obj,$title,$data,$sheetarray);
        }

	    // 文件名处理
	    if(!$fileName){  
	        $fileName = uniqid(time(),true);
	    }  

	    $objWrite = PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
	    ob_clean();
	  	// 网页下载
	    if($isDown){
	        header('pragma:public');
	        header("Content-Disposition:attachment;filename=$fileName.xlsx");  
	        $objWrite->save('php://output');
	        return true;
	    }
	    // 转码
	    $_fileName = characet($fileName);   
	    $_savePath = $savePath.$_fileName.'.xlsx';  
	    $objWrite->save($_savePath);
	  
	    return $savePath.$fileName.'.xlsx';
	}

	/**
     * 生成sheet
     */
	function ExportExcelSheet(&$obj,$title=array(), $data=array(),$sheetname,$zm=0){
		//横向单元格标识  
	    // $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
	    $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
						  'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA',
						  'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN',
						  'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ', 'BA',
						  'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN',
						  'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BU', 'BW', 'BX', 'BY', 'BZ', 'CA',
						  'CB', 'CC', 'CD', 'CE', 'CF', 'CG', 'CH', 'CI', 'CJ', 'CK', 'CL', 'CM', 'CN');  
	    $obj->createSheet($zm);
	    $obj->setActiveSheetIndex($zm);
	    $obj->getActiveSheet($zm)->setTitle($sheetname);
	    $_row = 1;   //设置纵向单元格标识  
	    if($title){  
	        $_cnt = count($title);  
	        $obj->getActiveSheet($zm)->mergeCells('A'.$_row.':'.$cellName[$_cnt-1].$_row);   //合并单元格  
	        $obj->setActiveSheetIndex($zm)->setCellValue('A'.$_row, '数据导出：'.date('Y-m-d H:i:s'));  //设置合并后的单元格内容  
	        $_row++;  
	        $i = 0;  
	        foreach($title AS $v){   //设置列标题  
	            $obj->setActiveSheetIndex($zm)->setCellValue($cellName[$i].$_row, $v);  
	            $i++;  
	        }  
	        $_row++;  
	    }
	    //填写数据  
	    if($data){  
	        $i = 0;  
	        foreach($data AS $_v){  
	            $j = 0;  
	            foreach($_v AS $_cell){  
	                $obj->getActiveSheet($zm)->setCellValue($cellName[$j] . ($i+$_row), $_cell);  
	                $j++;  
	            }  
	            $i++;  
	        }  
	    }
	}

	function characet($data){

	  if( !empty($data) ){
	    $fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5')) ;
	    if( $fileType != 'UTF-8'){
	      $data = mb_convert_encoding($data ,'utf-8' , $fileType);
	    }
	  }
	  return $data;
	}

	function getAgeByID($id){ 
		//过了这年的生日才算多了1周岁 
        if(empty($id)) return ''; 
        $date=strtotime(substr($id,6,8));
		//获得出生年月日的时间戳 
        $today=strtotime('today');
		//获得今日的时间戳 
        $diff=floor(($today-$date)/86400/365);
		//得到两个日期相差的大体年数 
		//strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比 
        $age=strtotime(substr($id,6,8).' +'.$diff.'years')>$today?($diff+1):$diff; 
  
        return $age; 
    }

    //代收授权
	function Warrant($data){
	    $url="http://jdc.woaicq.top/upacp_demo_dk/service/Warrant.php";
	    // $data=[
	    //   'orderId'=>'201802261001',//订单号
	    //   'phoneNo'=>"18166322955",//电话号码
	    //   'accNo'=>"6212263100008613973",//银行卡号
	    //   'certifId'=>"500225199308200736",//身份证号码
	    //   'customerNm'=>"周彦吉"//姓名
	    //   ];
	    // var_dump($data,'22222');die;
	   return HttpPost($url,$data);
	    
	  }


    //生成合同
    function createDocumentPost($orderId)
    {
        $order_db = M('order');
        $city_db = M('city');
        $cars_db = M('cars');
        $order_res = $order_db
            -> join('jdc_user on jdc_user.id=jdc_order.uid')
            ->where('orderid='.$orderId) -> find();
        $city_res = $city_db -> where('id='.$order_res['provinceid'].' or id='.$order_res['cityid']) -> select();
        $cars_res = $cars_db -> where('carnum='.$order_res['carnum']) -> find();
        $city = '';
        foreach ($city_res as $k => $v) {
            $city .= $city_res[$k]['name'];
        }
        $APIKEY = C('APPKEY');//安全秘钥
        $url = C('LINGURL')."api/template/v4/createDocument";
        $templateId = C('TEMPLATEID');
        $templateParams = array(
            "apiKey"=>$APIKEY,
            "templateId"=>$templateId,
            "smsRequred"=>"false",
            "wechatRequred"=>"false",
            "redirectUri" => $_SERVER['SERVER_NAME']."/Home/login/getDocument?orderId=".$orderId,
            "keyValues"=>array(
                array("key"=>"Text1", "value"=>$order_res['contract']),
                array("key"=>"Text2", "value"=>$order_res['fullanme']),
                array("key"=>"Text3", "value"=>$city),
                array("key"=>"Text4", "value"=>date('Y年m月d日',time())),
                array("key"=>"Text5", "value"=>$order_res['fullanme']),
                array("key"=>"Text6", "value"=>$order_res['address']),
                array("key"=>"Text7", "value"=>'/'),
                array("key"=>"Text8", "value"=>$order_res['identify']),
                array("key"=>"Text9", "value"=>$order_res['address']),
                array("key"=>"Text10", "value"=>$order_res['tel']),
                array("key"=>"Text11", "value"=>'/'),
                array("key"=>"Text12", "value"=>'/'),
                array("key"=>"Text13", "value"=>$order_res['tel']),
                array("key"=>"Text14", "value"=>$order_res['bank']),
                array("key"=>"Text15", "value"=>$order_res['banker']),
                array("key"=>"Text16", "value"=>$order_res['banknum']),
                array("key"=>"Text17", "value"=>$cars_res['month_pay']),
                array("key"=>"Text18", "value"=>$order_res['address']),
                array("key"=>"Text19", "value"=>$order_res['fullanme']),
                array("key"=>"Text20", "value"=>$order_res['tel']),
                array("key"=>"Text21", "value"=>'/'),
                array("key"=>"Text22", "value"=>'/'),
                array("key"=>"Text23", "value"=>date('Y年m月d日',time())),
                array("key"=>"Text24", "value"=>date('Y年m月d日',time())),
            ),
            "signners"=>array(//签名人信息
                array(//签名人信息2
                    "email"=>"",
                    "userName"=>$order_res['fullanme'],
                    "orgName"=>"",
                    "phone"=>$order_res['tel'],
                    "signatureKey"=>"重庆嘉时汽车经纪服务有限公司"
                ),
            )
        );

        $templateParams= json_encode($templateParams);
        $resultJson =  http_post_json($url,$templateParams);
        $resultJson = json_decode($resultJson, 'array');
        if ($resultJson['status'] == 'success') {
            $order_db -> where('orderid='.I('request.orderId'))
                -> save(['contract_status' => 1,
                    'fileDetailUri' => $resultJson['fileDetailUri'],
                    'documentId' => $resultJson['documentId'],
                    'lingQianUrl' => $resultJson['signnerUri'][0]['url']
                ]);
        }
        return $resultJson;
    }
    function createPersonalDocumentPost($templateParams)
    {
        $url = C('LINGURL')."api/template/v4/createDocument";
        $templateParams= json_encode($templateParams);
        $resultJson =  http_post_json($url,$templateParams);
        return json_decode($resultJson, 'array');
    }

    function getPersonalDocument($id)
    {
        $wayuser_db = M('wayuser');
        $wayuser = $wayuser_db -> where('id='.$id) -> find();
        $url= C('LINGURL')."api/template/v4/getDocument";
        $APIKEY = C('APPKEY');//安全秘钥
        $documentId = $wayuser['documentId'];
        $documentData = array(
            "apiKey" => $APIKEY,//接口调用授权码
            "documentId"=>$documentId //文档编号
        );
        $data = json_encode($documentData);
        $result = http_post_json($url, $data);
        $result = json_decode($result, 'array');
        $pdf = base64_decode($result['pdfBase64']);
        ossPutObject('Public/Uploads/contracts/'.$wayuser['name'].'-'.$documentId.'.pdf',$pdf);
    }

    function addSeal()
    {
        $url = C('LINGURL')."/api/seal/add";
        $APIKEY = C('APPKEY');//安全秘钥
        $imageBase64 = base64EncodeImage('./Public/Image/2.png');
        $data = [
            'apiKey' => $APIKEY,
            'sealName' => '重庆嘉时汽车经纪服务有限公司',
            'imageBase64' => $imageBase64
        ];
        $result = http_post_json($url, json_encode($data));
        $result = json_decode($result, 'array');
        return $result;
    }

    //合同下载
    function getDocument($orderId)
    {
        $order_db = M('order');
        $user = M('user');
        $order_res = $order_db -> where('orderid='.$orderId) -> find();
        $user_res = $user -> where('id='.$order_res['uid']) -> find();
        $url= C('LINGURL')."api/template/v4/getDocument";
        $APIKEY = C('APPKEY');//安全秘钥
        $documentId = $order_res['documentId'];
        $documentData = array(
            "apiKey" => $APIKEY,//接口调用授权码
            "documentId"=>$documentId //文档编号
        );
        $data = json_encode($documentData);
        $result = http_post_json($url, $data);
        $result = json_decode($result, 'array');
        $pdf = base64_decode($result['pdfBase64']);
        ossPutObject('Public/Uploads/contracts/'.$user_res['fullanme'].'-'.$documentId.'.pdf',$pdf);

    }

    //获取合同的状态
    function getDocumentStatus($documentId)
    {
        $url = C('LINGURL')."api/template/v4/getDocumentStatus";
        $APIKEY = C('APPKEY');//安全秘钥
        $data = [
            'apiKey' => $APIKEY,
            'documentId' => $documentId
        ];
        $result = http_post_json($url, json_encode($data));
        $result = json_decode($result, 'array');
        $result['documentId'] = $documentId;
        return $result;
    }

    //签署撤回
    function recall($orderId)
    {
        $order_db = M('order');
        $order_res = $order_db -> where('orderid='.$orderId) -> find();
        $url = C('LINGURL')."api/template/v4/recall";
        $APIKEY = C('APPKEY');//安全秘钥
        $documentId = $order_res['documentId'];
        $data = [
            'apiKey' => $APIKEY,
            'documentId' => $documentId
        ];
        $result = http_post_json($url, json_encode($data));
        $result = json_decode($result, 'array');
        return $result;
    }

    //签署作废
    function cancellation($orderId)
    {
        $order_db = M('order');
        $order_res = $order_db -> where('orderid='.$orderId) -> find();
        $url = C('LINGURL')."api/template/v4/cancellation";
        $APIKEY = C('APPKEY');//安全秘钥
        $documentId = $order_res['documentId'];
        $data = [
            'apiKey' => $APIKEY,
            'documentId' => $documentId
        ];
        $result = http_post_json($url, json_encode($data));
        $result = json_decode($result, 'array');
        return $result;
    }

    function http_post_json($url, $jsonStr)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST,1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); // 检查证书中是否设置域名
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr)
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (curl_errno($url)) {
            $res = curl_error($url);
        };
        curl_close($url);
        return $response;
    }

	function ImgThumb($imgpath){
		if($imgpath){
			$image  = new \Think\Image();
			$image->open($imgpath);
        	$image->thumb(1280, 1280)->save($imgpath);
		}
	}

    function base64EncodeImage($image_file) {
        $imageData = base64_encode(file_get_contents($image_file));
        $base64_image = 'data:'.mime_content_type($image_file).';base64,'.$imageData;
        return $base64_image;
    }
    function getImagetype($filename)
    {	
    	$exten = explode('.', $filename);
    	$last=$exten[count($exten)-1];
        $fileType = '';
        switch ($last) {
            case "jpg":
                $fileType = 'jpg';
                break;
            case "bmp":
                $fileType = 'bmp';
                break;
            case "png":
                $fileType = 'png';
                break;
            case "jpeg":
                $fileType = 'jpeg';
                break;
            default:
                $fileType = false;
        }
        return $fileType;
    }